const filterKeys = (keys: Array<string>, userId: string):Array<string> => (
    keys.filter((key: string) => key.includes(`${userId}`))
);

const findIndex = (item: any, userId?: string) => {
    const { profile } = item || {};
    item = !!profile ? profile : item;
    return item.userId === userId;
}

export default (state?: any, userId?: string, loginUserId?: string, callback?: Function) => {
    const _orders = Object.keys(state) as Array<string>;
    const keys = filterKeys(_orders, loginUserId || ``);

    keys.forEach((orderBy: string) => {

        const list = state[orderBy] || [];

        const index = list.findIndex((item: any) => (
            findIndex(item, userId)
        ))

        if (index > -1) {
            const _item = (
                list[index] as any
            )

            const {
                profile
            } = _item;

            if(!!callback) {
                callback(!!profile ? profile : _item);
            }

            if (!profile) {
                list[index] = {..._item}
            }
            else {
                list[index].profile = {...profile};
            }

            state[orderBy] = [...list];
        }
    })
    return {
        ...state
    }
}